// secretKey = a22d5a92acded6fd2ee005db1ac9e68f
// appId = wxe42ba8b7f8f5e8ff

function tokenHeader() {
  const token = wx.getStorageSync("token")
  //const token = getApp().globalData.token
  return token ? {
    Authorization: token
  } : {}
}

function fnFail(err, fail) {
  if (fail) {
    fail(err)
    return
  }
}

function successFunction(res, {
  success,
  fail,
  complete
}) {
  const statusCode = res.statusCode
  if (statusCode !== 200) {
    fnFail(new Error(`HTTPCode = ${statusCode}`), fail)
    return
  }
  const resData = res.data
  const {
    status,
    code,
    message,
    data
  } = resData
  if (status === 0) {
    const err = new Error(`${code}:${message}`)
    err.code = code
    err.message = message
    fnFail(err, fail)
  } else {
    success(data)
  }
}

function buildParamString(param) {
  const kvs = Object.entries(param).map(([k, v]) => `${k}=${v}`)
  return kvs.join("&")
}

function postJson(url, param, {
  success,
  fail,
  complete
}, header) {
  const p = {
    url,
    data: param,
    header: {
      ...header,
      ...tokenHeader(),
      "Content-Type": "application/json"
    },
    method: 'POST',
    dataType: 'json',
    success: function (res) {
      successFunction(res, {
        success,
        fail,
        complete
      })
    },
    complete: function () {
      if (complete) complete()
    }
  }
  wx.request(p)
}

function postParam(url, param, {
  success,
  fail,
  complete
}, header) {
  const ps = buildParamString(param)
  const p = {
    url: ps ? `${url}?${ps}` : url,
    header: {
      ...header,
      ...tokenHeader(),
    },
    method: 'POST',
    dataType: 'json',
    success: function (res) {
      successFunction(res, {
        success,
        fail,
        complete
      })
    },
    complete: function () {
      if (complete) complete()
    }
  }
  wx.request(p)
}

function get(url, param, {
  success,
  fail,
  complete
}) {
  const ps = buildParamString(param)
  const p = {
    url: ps ? `${url}?${ps}` : url,
    method: 'GET',
    header: {
      ...tokenHeader(),
    },
    success: function (res) {
      successFunction(res, {
        success,
        fail,
        complete
      })
    },
    complete: function () {
      if (complete) complete()
    }
  }
  wx.request(p)
}


function del(url, param, {
  success,
  fail,
  complete
}) {
  const ps = buildParamString(param)
  const p = {
    url: ps ? `${url}?${ps}` : url,
    method: 'DELETE',
    header: {
      ...tokenHeader(),
    },
    success: function (res) {
      successFunction(res, {
        success,
        fail,
        complete
      })
    },
    complete: function () {
      if (complete) complete()
    }
  }
  wx.request(p)
}


module.exports = {
  postParam,
  postJson,
  get,
  del
}